// JavaScript Document
const FPSlimit = 30;
var curFPS = 0;
var numFramesDrawn = 0;
var fpsInterval = setInterval(updateFPS, 1000);
var numResourcesLoaded = 0;
var totalResources = 1;
var gameModeSelected = false;
var gameModes = null;
var canvas = null;
var ctx = null;
var images = {};
var grid = 32;
var mapLoaded = false;
var contentLoaded = false;
var players = new Array();
var lvl = 1;
var keys = new Array();
var mapFiles = new Array();
var keylock = new Array();

window.addEventListener('keydown', keyDown, true);
window.addEventListener('keyup', keyUp, true);
window.addEventListener('blur', canvasLostFocus, true);

window.onload = init;

function init() {
    canvas = document.getElementById('canvas');
    ctx = canvas.getContext("2d");
    loadContext();
    initTwoPlayerGame();
    initGameModes();

    setInterval(gameLoop, 1000/FPSlimit);
}
function initOnePlayerGame(){
    var p1 = new Player();
    p1.assignKeys(KeyBoardType.WASD);
    p1.assignKeys(KeyBoardType.ARROWS);
    players.push(p1);
    //initAI()
}

function initGameModes() {
    gameModes = new GameModes(canvas);
    gameModes.addMode(new Mode(100,40,400,120,"Player vs Player"));
    gameModes.addMode(new Mode(100,200,400,120,"Player vs Computer"));
    gameModes.addMode(new Mode(100,340,400,120, "Multiplayer"));
}

function initTwoPlayerGame(){
    var p1 = new Player();
    p1.assignKeys(KeyBoardType.WASD);
    players.push(p1);
    var p2 = new Player();
    p2.assignKeys(KeyBoardType.ARROWS);
    players.push(p2);

}

function loadContext () {
    loadImage("TilesSprite2");
}

level = {
    name:"Error 100 - Level not found",
    map:[],
    spawnPos: {
        "x": 0,
        "y": 0
    }
};

function canvasLostFocus(evt) {
    keys = new Array();
}

function updateFPS() {
	curFPS = numFramesDrawn;
	numFramesDrawn = 0;
}		

function gameLoop() {
	if (contentLoaded && mapLoaded) {
        if (gameModeSelected){
            update();
            clear();
            draw();
        } else {
            draw();
            gameModes.draw();
        }
    } else {
        drawLoading();
    }
}

function update() {

	for (var i = 0; i < players.length; i++) {
        players[i].update();
        updateArrowKeys(players[i]);
    }
	//updateArrowKeys();
}

function draw() {
	drawWorld();
    for (var i = 0; i < players.length; i++) {
        players[i].draw();
    }
	drawHud();
}

function drawWorld() {
	mapHorizontalSize = level.map.length;
	mapVerticalSize = level.map[0].length;
	for (var i = 0; i < mapHorizontalSize; i++) {
		for (var j = 0; j < mapVerticalSize; j++) {
			var t = level.map[i][j];
			var tnum = parseInt(t.substr(1, 2));
			switch (t.charAt(0)) {
				case 'f':
					drawGridObject(images["TilesSprite2"], tnum, 1, i * grid, j * grid);
					break;
				case 'w':
					drawGridObject(images["TilesSprite2"], tnum, 2, i * grid, j * grid);
					break;
			}
		}
	}
}

function drawHud() {
	ctx.save();
	ctx.setTransform(1, 0, 0, 1, 0, 0);
	
	//FPS
	ctx.fillStyle = "#000";
	ctx.font = "bold 12px sans-serif";
	ctx.fillText("fps: " + Math.min(curFPS,FPSlimit) + "/" + FPSlimit, 10, 20);
	++numFramesDrawn;
	
	ctx.restore();
}

function drawLoading() {
	ctx.save();
	ctx.setTransform(1, 0, 0, 1, 0, 0);
	
	ctx.clearRect(0, 0, canvas.width, canvas.height);
	
	ctx.fillStyle = "#FFF";
	
	ctx.font = 'bold 30px sans-serif';
	ctx.lineWidth = 1;
	ctx.strokeStyle = "#000";
	var dots = "";
	for (var i = 1; i < (numFramesDrawn / 15 % 30); i++) {
		dots += ".";
		if (i > 2) {
			break;
		}
	}
	var numResourcesLoaded = 0;
	var totalResources = 1;
	ctx.fillText('Loading' + dots, canvas.width / 2 - 50, canvas.height / 2 - 20);
	ctx.strokeText('Loading' + dots, canvas.width / 2 - 50, canvas.height / 2 - 20);
		ctx.fillText(numResourcesLoaded + "/" + totalResources, canvas.width / 2 - 15, canvas.height / 2 + 10);
	ctx.strokeText(numResourcesLoaded + "/" + totalResources, canvas.width / 2 - 15, canvas.height / 2 + 10);
	++numFramesDrawn;
	
	ctx.restore();
}

function clear() {
	// Store the current transformation matrix
	ctx.save();
	// Use the identity matrix while clearing the canvas
	ctx.setTransform(1, 0, 0, 1, 0, 0);
	ctx.clearRect(0, 0, canvas.width, canvas.height);
	// Restore the transform
	ctx.restore();
}